package com.starpl.mobile.android.monthunsae.november.handler;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.starpl.mobile.android.monthunsae.november.R;
import com.starpl.mobile.android.monthunsae.november.activity.CommunityCommentActivity;
import com.starpl.mobile.android.monthunsae.november.activity.SettingProfileImageActivity;
import com.starpl.mobile.android.monthunsae.november.domain.UserInfo;
import com.starpl.mobile.android.platform.command.StarplCommand;
import com.starpl.mobile.android.platform.common.StarplUtil;
import com.starpl.mobile.android.platform.common.base.BaseApplication;
import com.starpl.mobile.android.platform.common.image.ImageDownloader;
import com.starpl.mobile.android.platform.common.network.HttpHandler;
import com.starpl.mobile.android.platform.component.BaseListHandler;
import com.starpl.mobile.android.platform.domain.CommunityArticle;


/**
 * 프로필의 사용자 댓글를 위한 리스트 핸들러
 * 
 * @author 우연화, 박우람
 * @since 2011.03.17
 */
public class ProfileListHandler extends BaseListHandler implements OnClickListener
{
	private static final String DEFAULT_IMAGE_PATH = "http://shared.starpl.com/images/home/common/img_profile.gif";
	private static final String TAG = "ProfileListHandler";
	private ArrayList<CommunityArticle> mList;
	private int mNextPage;
	private String mUserId;
	
	private ImageView mIvProfileImage;
	private TextView mTvUsername;
	private TextView mTvNickname;
	private TextView mTvBirthGender;
	
	private LinearLayout mLlStarplUser;
	private LinearLayout mLlMobileUser;
	

	/**
	 * 기본 생성자
	 * 
	 * @param activity
	 *            엑티비티
	 * @param userId
	 *            사용자 아이디
	 * @param keywordIdx
	 *            키워드 인덱스
	 */
	public ProfileListHandler(Activity activity, String userId)
	{
		super(activity);

		this.mUserId = userId;
		this.mList = new ArrayList<CommunityArticle>();
		this.mNextPage = 1;
	}
	
	/**
	 * 프로필 이미지뷰를 반환합니다.
	 * 
	 * @return 이미지뷰
	 */
	public ImageView getProfileImage()
	{
		return mIvProfileImage;
	}
	
	public void setHeaderView(Object result)
	{
		JSONObject object = (JSONObject) result;
		try
		{
			JSONObject data = object.getJSONObject("data");

			// 유저 프로필 정보를 받아온다.
			String profileImgPath = data.getString("profileImgPath");
			String nickname = data.getString("starName");
			
			mIvProfileImage.setOnClickListener(ProfileListHandler.this);
			
			mTvNickname.setText(nickname);
			
			UserInfo userInfo = (UserInfo) BaseApplication.getGlobalPersistent("userInfo");
			String userNickname = userInfo.getNickName();
			
			if(profileImgPath.equals(DEFAULT_IMAGE_PATH)&&userNickname.equals(nickname))
			{
				mIvProfileImage.setBackgroundResource(R.drawable.img_picture_change);
			}
			else
			{
				ImageDownloader.download(profileImgPath, mIvProfileImage, true);
			}

			// 모바일에서 가입 후, 개인정보를 입력하지 않은 회원, 내 프로필이 아닌경우
			if(!object.isNull("extData1"))
			{
				mLlStarplUser.setVisibility(LinearLayout.GONE);
				mLlMobileUser.setVisibility(LinearLayout.VISIBLE);
			}
			// 개인정보가 입력된 회원
			else
			{
				String userName = data.getString("userName");
				String birthday = "미입력";

				if(!data.isNull("birthDate"))
				{
					birthday = data.getString("birthDate");
				}

				boolean sexFlag = data.getBoolean("sexFlag");

				// 뷰 상태 값을 받아온다.
				boolean friendFlag = data.getBoolean("friendFlag");
				String birthViewCode = data.getString("birthViewCode");
				String sexViewCode = data.getString("sexViewCode");

				mLlStarplUser.setVisibility(LinearLayout.VISIBLE);
				mLlMobileUser.setVisibility(LinearLayout.GONE);


				String birthdayGender = null;
				String sex = null;

				// 내 프로필인 경우
				if(userNickname.equals(nickname))
				{
					birthdayGender = birthday.substring(0, 10);
					
					// 성별 데이터 처리
					if(sexFlag)
					{
						sex = " (남)";
					}
					else
					{
						sex = " (여)";
					}
				}
				// 내 프로필이 아닌경우
				else
				{
					// 생일정보 전체공개
					if(birthViewCode.equals("USBV10"))
					{
						birthdayGender = birthday.substring(0, 10);
					}
					// 생일정보 친구공개
					else if(birthViewCode.equals("USBV20"))
					{
						if(friendFlag)
						{
							birthdayGender = birthday.substring(0, 10);
						}
						else
						{
							birthdayGender = "(생일정보 친구공개)";
						}
					}
					// 생일정보 비공개
					else if(birthViewCode.equals("USBV30"))
					{
						birthdayGender = "(생일정보 비공개)";
					}

					// 성별 데이터 처리
					if(sexFlag)
					{
						sex = " (남)";
					}
					else
					{
						sex = " (여)";
					}

					// 성별정보 전체공개
					if(sexViewCode.equals("USSV10"))
					{
						birthdayGender = birthdayGender + sex;
					}
					// 성별정보 친구공개
					else if(sexViewCode.equals("USSV20"))
					{
						if(friendFlag)
						{
							birthdayGender = birthdayGender + sex;
						}
						else
						{
							birthdayGender = birthdayGender + " (성별정보 친구공개)";
						}
					}
					// 성별정보 비공개
					else if(sexViewCode.equals("USSV30"))
					{
						birthdayGender = birthdayGender + " (성별정보 비공개)";
					}
				}
				
				// 유저정보 세팅(유저이름, 생일, 성별)
				mTvUsername.setText(userName);
				mTvBirthGender.setText(birthdayGender);
			}
		}
		catch(JSONException e)
		{
			Log.e(TAG, e.getMessage());
		}
		
		
//		mTvUsername
//		mTvNickname
//		mTvBirthGender
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.starpl.platform.component.BaseListHandler#getArrayList()
	 */
	@Override
	public ArrayList<?> getArrayList()
	{
		// USAGE : 반환할 리스트 객체 정의
		return mList;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.starpl.platform.component.BaseListHandler#getRowView(int,
	 * android.view.View)
	 */
	@Override
	public View getRowView(int position, View convertView)
	{
		if(convertView == null)
		{
			// USAGE : 인플레이터 활용
			convertView = inflate(R.layout.community_default_row);
		}

		ImageView ivProfileImage = (ImageView) convertView.findViewById(R.id.community_default_row_iv_profile);
		TextView tvComment = (TextView) convertView.findViewById(R.id.community_default_row_tv_comment);
		TextView tvNickName = (TextView) convertView.findViewById(R.id.community_default_row_tv_nickname);
		TextView tvWrittenDate = (TextView) convertView.findViewById(R.id.community_default_row_tv_date);
		TextView tvReplyLabel = (TextView) convertView.findViewById(R.id.community_default_row_tv_reply_label);
		TextView tvReplyCount = (TextView) convertView.findViewById(R.id.community_default_row_tv_reply_count);
		ImageView ivThumbnail = (ImageView) convertView.findViewById(R.id.community_default_row_iv_thumbnail);

		TextView tvToNickName = (TextView) convertView.findViewById(R.id.community_re_reply_row_tv_to_nickname);
		LinearLayout llOriginalLayout = (LinearLayout) convertView.findViewById(R.id.community_reply_row_ll_origin_article);
		ImageView ivOriginalProfileImage = (ImageView) convertView.findViewById(R.id.community_reply_row_iv_origin_profile);
		TextView tvOriginalComment = (TextView) convertView.findViewById(R.id.community_reply_row_tv_origin_comment);
		ImageView ivBadge = (ImageView) convertView.findViewById(R.id.community_default_row_iv_badge);

		// 사용자 프로필
		CommunityArticle article = (CommunityArticle) mList.get(position);
		String profileUrl = StarplUtil.addSizeTag(article.getProfileImgPath(), "60", "profile");
		ImageDownloader.download(profileUrl, ivProfileImage, true);

		// 글
		tvComment.setText(article.getSubject());

		// 닉네임
		tvNickName.setText(article.getStarName());

		// 글 작성 시각
		tvWrittenDate.setText(article.getWrittenDate());

		// 댓글 숫자
		int replyCount = article.getReplyCount();
		if(replyCount > 0)
		{
			tvReplyLabel.setVisibility(TextView.VISIBLE);
			tvReplyCount.setVisibility(TextView.VISIBLE);
			tvReplyCount.setText("(" + article.getReplyCount() + ")");
		}
		else
		{
			tvReplyLabel.setVisibility(TextView.INVISIBLE);
			tvReplyCount.setVisibility(TextView.INVISIBLE);
		}

		// 첨부 이미지
		String thumbnail = article.getPostImgPath();
		if(thumbnail != null && thumbnail.length() > 0)
		{
			thumbnail = StarplUtil.addSizeTag(article.getPostImgPath(), "66", "thumbnail");
			ImageDownloader.download(thumbnail, ivThumbnail);
			ivThumbnail.setVisibility(ImageButton.VISIBLE);
		}
		else
		{
			ivThumbnail.setVisibility(ImageButton.GONE);
		}

		// 글의 상태에 맞는 추가 정보 표기
		switch(article.getType())
		{
		case CommunityArticle.TYPE_ORIGINAL:
			tvToNickName.setVisibility(TextView.GONE);
			llOriginalLayout.setVisibility(LinearLayout.GONE);
			break;
		case CommunityArticle.TYPE_REPLY:
			tvToNickName.setVisibility(TextView.GONE);
			llOriginalLayout.setVisibility(LinearLayout.VISIBLE);
			thumbnail = StarplUtil.addSizeTag(article.getParentProfileImgPath(), "30", "thumbnail");
			ImageDownloader.download(thumbnail, ivOriginalProfileImage, true);
			tvOriginalComment.setText(article.getParentSubject());
			break;
		case CommunityArticle.TYPE_REPLY_OF_REPLY:
			tvToNickName.setVisibility(TextView.VISIBLE);
			tvToNickName.setText("To. " + article.getBrotherStarName());
			llOriginalLayout.setVisibility(LinearLayout.VISIBLE);
			thumbnail = StarplUtil.addSizeTag(article.getParentProfileImgPath(), "30", "thumbnail");
			ImageDownloader.download(thumbnail, ivOriginalProfileImage, true);
			tvOriginalComment.setText(article.getParentSubject());
			break;
		}

		// 배지 정보 표시
		int badgeType = article.getBadgeType();
		switch(badgeType)
		{
		case 1:
			ivBadge.setVisibility(ImageView.VISIBLE);
			ivBadge.setImageResource(R.drawable.icon_master);
			break;
		case 2:
			ivBadge.setVisibility(ImageView.VISIBLE);
			ivBadge.setImageResource(R.drawable.icon_senior);
			break;
		case 3:
			ivBadge.setVisibility(ImageView.VISIBLE);
			ivBadge.setImageResource(R.drawable.icon_junior);
			break;
		default:
			ivBadge.setVisibility(ImageView.GONE);
		}

		// 태그 입력
		convertView.setTag(position);

		return convertView;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.starpl.platform.component.BaseListHandler#onRowClick(android.view
	 * .View)
	 */
	@Override
	public void onRowClick(View v)
	{
		UserInfo userInfo = (UserInfo) BaseApplication.getGlobalPersistent("userInfo");
		CommunityArticle article = mList.get((Integer) v.getTag());
		Bundle extras = new Bundle();
		extras.putString("userId", userInfo.getUserId());
		extras.putInt("userIdx", userInfo.getUserIdx());
		extras.putInt("postIdx", article.getPostIdx());

		getNewActivity().setBundle(extras).setTargetActivity(CommunityCommentActivity.class).show();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.starpl.platform.component.BaseListHandler#onRowClear()
	 */
	@Override
	public void onRowClear()
	{
		// USAGE : 리프레시등에 의하여 데이터를 삭제할경우 사용되는 로직
		mList.clear();
		mNextPage = 1;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.starpl.platform.component.BaseListHandler#loadContent()
	 */
	@Override
	public void loadContent()
	{
		HttpHandler httpHandler = new HttpHandler(mParentActivity, null)
		{
			@Override
			public void didSucceed(Object result)
			{
				try
				{
					JSONObject articleObject = (JSONObject) result;
					JSONArray articleArray = articleObject.getJSONArray("data");

					// 글 리스트를 객체화 한다.
					int articleCount = articleArray.length();
					CommunityArticle article;

					for(int i = 0 ; i < articleCount ; i++)
					{
						article = new CommunityArticle(articleArray.getJSONObject(i));

						mList.add(article);
					}

					// 다음페이지 처리를 한다.
					JSONObject pageObject = articleObject.getJSONObject("extData1");
					mNextPage = pageObject.getInt("nextPageNum");
					notifyDataSetChanged();

					// 다음 페이지가 있을경우 자동 다음페이지를 읽을수 있도록 설정한다.
					if(mNextPage > 0)
					{
						// USAGE : 페이징처리를 하고 있고 다음페이지가 존재할 경우 다음을 호출해야 한다.
						toggleLockListView();
					}
					else
					{
						mFooterView.setVisibility(View.GONE);
					}
				}
				catch(JSONException e)
				{
					Log.e(TAG, e.getMessage());
				}
			}
		};

		StarplCommand.getPost(httpHandler, mUserId, mNextPage++);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.starpl.platform.component.BaseListHandler#getHeaderView()
	 */
	@Override
	public View getHeaderView()
	{
		final View convertView = inflate(R.layout.profile_header);
		HttpHandler httpHandler = new HttpHandler(mParentActivity)
		{
			@Override
			public void didSucceed(Object result)
			{
				JSONObject object = (JSONObject) result;
				try
				{
					JSONObject data = object.getJSONObject("data");

					// 유저 프로필 정보를 받아온다.
					String profileImgPath = data.getString("profileImgPath");
					String nickname = data.getString("starName");
					
					mIvProfileImage = (ImageView) convertView.findViewById(R.id.profile_header_iv_profile);
					mTvNickname = (TextView) convertView.findViewById(R.id.profile_header_tv_nickname);

					mIvProfileImage.setOnClickListener(ProfileListHandler.this);
					
					mTvNickname.setText(nickname);
					
					UserInfo userInfo = (UserInfo) BaseApplication.getGlobalPersistent("userInfo");
					String userNickname = userInfo.getNickName();
					
					if(profileImgPath.equals(DEFAULT_IMAGE_PATH)&&userNickname.equals(nickname))
					{
						mIvProfileImage.setBackgroundResource(R.drawable.img_picture_change);
					}
					else
					{
						ImageDownloader.download(profileImgPath, mIvProfileImage, true);
					}

					boolean mobileUser = false;
					
					if(!object.isNull("extData1"))
					{
						JSONObject extData1 = object.getJSONObject("extData1");
						mobileUser = extData1.isNull("mobileUserFlag") ? false : extData1.getBoolean("mobileUserFlag");
					}
					
					// 모바일에서 가입 후, 개인정보를 입력하지 않은 회원, 내 프로필이 아닌경우
					if(mobileUser)
					{
						mLlStarplUser = (LinearLayout) convertView
								.findViewById(R.id.profile_header_ll_regist_info);
						mLlMobileUser = (LinearLayout) convertView
								.findViewById(R.id.profile_header_ll_unregist_info);

						mLlStarplUser.setVisibility(LinearLayout.GONE);
						mLlMobileUser.setVisibility(LinearLayout.VISIBLE);
					}
					// 개인정보가 입력된 회원
					else
					{
						String userName = data.getString("userName");
						String birthday = "미입력";

						if(!data.isNull("birthDate"))
						{
							birthday = data.getString("birthDate");
						}

						boolean sexFlag = data.getBoolean("sexFlag");

						// 뷰 상태 값을 받아온다.
						boolean friendFlag = data.getBoolean("friendFlag");
						String birthViewCode = data.getString("birthViewCode");
						String sexViewCode = data.getString("sexViewCode");

						mLlStarplUser = (LinearLayout) convertView
								.findViewById(R.id.profile_header_ll_regist_info);
						mLlMobileUser = (LinearLayout) convertView
								.findViewById(R.id.profile_header_ll_unregist_info);

						mLlStarplUser.setVisibility(LinearLayout.VISIBLE);
						mLlMobileUser.setVisibility(LinearLayout.GONE);

						mTvUsername = (TextView) convertView.findViewById(R.id.profile_header_tv_username);
						mTvBirthGender = (TextView) convertView
								.findViewById(R.id.profile_header_tv_birthday_gender);

						String birthdayGender = null;
						String sex = null;

						// 내 프로필인 경우
						if(userNickname.equals(nickname))
						{
							birthdayGender = birthday.substring(0, 10);
							
							// 성별 데이터 처리
							if(sexFlag)
							{
								sex = " (남)";
							}
							else
							{
								sex = " (여)";
							}
						}
						// 내 프로필이 아닌경우
						else
						{
							// 생일정보 전체공개
							if(birthViewCode.equals("USBV10"))
							{
								birthdayGender = birthday.substring(0, 10);
							}
							// 생일정보 친구공개
							else if(birthViewCode.equals("USBV20"))
							{
								if(friendFlag)
								{
									birthdayGender = birthday.substring(0, 10);
								}
								else
								{
									birthdayGender = "(생일정보 친구공개)";
								}
							}
							// 생일정보 비공개
							else if(birthViewCode.equals("USBV30"))
							{
								birthdayGender = "(생일정보 비공개)";
							}

							// 성별 데이터 처리
							if(sexFlag)
							{
								sex = " (남)";
							}
							else
							{
								sex = " (여)";
							}

							// 성별정보 전체공개
							if(sexViewCode.equals("USSV10"))
							{
								birthdayGender = birthdayGender + sex;
							}
							// 성별정보 친구공개
							else if(sexViewCode.equals("USSV20"))
							{
								if(friendFlag)
								{
									birthdayGender = birthdayGender + sex;
								}
								else
								{
									birthdayGender = birthdayGender + " (성별정보 친구공개)";
								}
							}
							// 성별정보 비공개
							else if(sexViewCode.equals("USSV30"))
							{
								birthdayGender = birthdayGender + " (성별정보 비공개)";
							}
						}
						
						

						// 유저정보 세팅(유저이름, 생일, 성별)
						mTvUsername.setText(userName);
						mTvBirthGender.setText(birthdayGender);
					}
				}
				catch(JSONException e)
				{
					Log.e(TAG, e.getMessage());
				}
			}
		};

		StarplCommand.getUserInfo(httpHandler, mUserId);

		return convertView;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.starpl.platform.component.BaseListHandler#getFooterView()
	 */
	@Override
	public View getFooterView()
	{
		// USAGE : 푸터를 반환한다.
		return inflate(R.layout.community_footer);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.view.View.OnClickListener#onClick(android.view.View)
	 */
	@Override
	public void onClick(View v)
	{
		String myUserId = ((UserInfo) BaseApplication.getGlobalPersistent("userInfo")).getUserId();
		if(mUserId.equals(myUserId))
		{
			switch(v.getId())
			{
			case R.id.profile_header_iv_profile:
				getNewActivity()
					.setTargetActivity(SettingProfileImageActivity.class)
					.setRequestCode(0)
					.show();
				break;
			}
		}
	}

	@Override
	public void onInit()
	{
		// USAGE : 헤더뷰를 붙인다.
		showHeaderView();

		// USAGE : 푸터뷰를 붙인다.
		showFooterView();

		// USAGE : 어댑터를 붙인다. 실제로 데이터와 리스트뷰가 연결된다.
		setAdapter();

		// USAGE : 리스트의 데이터를 수동으로 호출한다.
		loadContent();
	}
}